package com.zsc.wxm.ysh.anjo.house.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.wxm.ysh.anjo.house.cache.EstateCacheService;
import com.zsc.wxm.ysh.anjo.house.mapper.EstateMapper;
import com.zsc.wxm.ysh.anjo.house.model.Estate;
import com.zsc.wxm.ysh.anjo.house.model.Images;
import com.zsc.wxm.ysh.anjo.house.model.Resources;
import com.zsc.wxm.ysh.anjo.house.service.EstateService;
import com.zsc.wxm.ysh.anjo.house.service.ImagesService;
import com.zsc.wxm.ysh.anjo.house.service.ResourcesService;
import com.zsc.wxm.ysh.anjo.result.PageResult;
import com.zsc.wxm.ysh.anjo.service.base.constant.OtherConstant;
import com.zsc.wxm.ysh.anjo.service.base.enums.resources.*;
import com.zsc.wxm.ysh.anjo.service.base.exception.AnjoException;
import com.zsc.wxm.ysh.anjo.service.base.model.es.dto.CrawlerDataDTO;
import com.zsc.wxm.ysh.anjo.service.base.model.es.vo.CrawlerDataVO;
import com.zsc.wxm.ysh.anjo.service.base.model.resources.dto.EstateDTO;
import com.zsc.wxm.ysh.anjo.service.base.model.resources.qo.EstateQuery;
import com.zsc.wxm.ysh.anjo.utils.ExceptionUtil;
import com.zsc.wxm.ysh.anjo.utils.PageUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Random;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author playmaker
 * @since 2021-01-04
 */
@Service
@Slf4j
public class EstateServiceImpl extends ServiceImpl<EstateMapper, Estate> implements EstateService {

    @Resource
    private ResourcesService resourcesService;

    @Resource
    private EstateCacheService estateCacheService;

    @Resource
    private ImagesService imagesService;

    private Random random = new Random();

    @Override
    public Long addEstate(EstateDTO estate) {
        Estate item = new Estate();
        BeanUtils.copyProperties(estate,item);
        item.setPropertyCost(new BigDecimal(estate.getPropertyCost()));
        this.save(item);
        return item.getId();
    }

    @Override
    public void updateEstate(EstateDTO estateDTO) {
        if (estateDTO.getId() == null) {
            throw new AnjoException("楼盘Id不能是空的", 100000);
        }
        Estate item = estateCacheService.getByIdCache(estateDTO.getId());
        BeanUtils.copyProperties(estateDTO, item);
        this.updateById(item);
        estateCacheService.removeByIdCache(item.getId());
    }

    @Override
    public PageResult listPage(EstateQuery query) {
        Page<Estate> page = new Page<>(query.getCurrPage(), query.getPageSize());
        LambdaQueryWrapper<Estate> queryWrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(query.getArea())) {
            queryWrapper.eq(Estate::getArea, query.getArea());
        }
        if (StringUtils.isNotBlank(query.getCity())) {
            queryWrapper.eq(Estate::getCity, query.getCity());
        }
        if (StringUtils.isNotBlank(query.getName())) {
            queryWrapper.like(Estate::getName, query.getName());
        }
        if (StringUtils.isNotBlank(query.getProvince())) {
            queryWrapper.eq(Estate::getProvince, query.getProvince());
        }
        if (query.getCreateTimeStart() != null) {
            queryWrapper.ge(Estate::getCreateTime, query.getCreateTimeStart());
        }
        if (query.getCreateTimeEnd() != null) {
            queryWrapper.le(Estate::getCreateTime, query.getCreateTimeEnd());
        }
        if (StringUtils.isNotBlank(query.getType())) {
            queryWrapper.eq(Estate::getType, query.getType());
        }
        page = baseMapper.selectPage(page, queryWrapper);
        PageUtil pageUtil = new PageUtil(page);
        return PageResult.ok(pageUtil.getList(), pageUtil.getTotal());
    }

    @Override
    public void deleteEstate(Long id) {
        LambdaQueryWrapper<Resources> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Resources::getEstateId,id);
        Assert.isTrue(CollUtil.isNotEmpty(resourcesService.list(queryWrapper)),"请先删除相应的房源信息");
        this.removeById(id);
        //删除缓存
        estateCacheService.removeByIdCache(id);
    }

    @Override
    public void batchAddEstateDataByFile(CrawlerDataDTO params) {
        log.info("batchAddEstateDataByFile()参数：{}", params);

        //读取data.json
        try {
            List<String> lines = FileUtils.readLines(new File(OtherConstant.JSON_DATA_PATH + "data.json"), "UTF-8");
            for (String line : lines) {
                CrawlerDataVO vo = JSON.parseObject(line, CrawlerDataVO.class);
                log.info("读取json对象，{}", vo);
                LambdaQueryWrapper<Estate> queryWrapper = Wrappers.lambdaQuery();
                queryWrapper.eq(Estate::getName, vo.getEstateName());
                if (CollUtil.isNotEmpty(this.list(queryWrapper))) {
                    //防止楼盘重复
                    continue;
                }
                Estate estate = new Estate();
                BeanUtils.copyProperties(params, estate);
                estate.setName(vo.getEstateName());
                estate.setPropertyCost(new BigDecimal(params.getPropertyCost()));
                estate.setAddress(params.getArea() + "-" + vo.getEstateName());
                this.save(estate);

                //房源
                Resources resources = new Resources();
                BeanUtils.copyProperties(vo,resources);
                resources.setBuildingNum(random.nextInt(50) + "栋");
                resources.setEstateId(estate.getId());
                resources.setBuidingFloorNum(100 + random.nextInt(300) + "号");
                resources.setBuildingUnit(10 + random.nextInt(500) + "号");
                resources.setCoveredArea(vo.getUseArea());
                resources.setOrientation(getToward(vo.getOrientation()));
                resources.setDecoration(WeltType.HARDCOVER.getValue());
                resources.setFacilities("1,2,3,4");
                resources.setConstact("王经理");
                resources.setPhone("18027753315");
                resources.setPaymentMethod(PaymentType.PAY_ONE_BET_ONE.getValue());
                resources.setRentMethod(getRentType(vo.getRentMethod()));
                resources.setStatus(HouseStatus.AVAILABLE.getValue());
                resources.setRent(new BigDecimal(vo.getRent()));
                resources.setHouseType(getHouseTypeByStr(vo.getHouseType()));
                resources.setTime(getTimeByStr(vo.getTime()));
                resourcesService.save(resources);

                //图片
                String defaultUrl = "https://playmaker.oss-cn-shenzhen.aliyuncs.com/anjo/";
                Images images = new Images();
                images.setImageUrl(defaultUrl + vo.getImage());
                images.setHouseResourcesId(resources.getId());
                imagesService.save(images);
            }
        } catch (IOException e) {
            log.error(ExceptionUtil.getMessage(e));
        }
    }

    @Override
    public Estate getOneById(Long id) {
        return estateCacheService.getByIdCache(id);
    }

    /**
     * 获取朝向
     *
     * @param str
     * @return
     */
    private Integer getToward(String str) {
        if (str.contains(TowardsType.EAST.getDesc())) {
            return TowardsType.EAST.getValue();
        } else if (str.contains(TowardsType.SOUTH.getDesc())) {
            return TowardsType.SOUTH.getValue();
        } else if (str.contains(TowardsType.WEAT.getDesc())) {
            return TowardsType.WEAT.getValue();
        } else if (str.contains(TowardsType.NORTH.getDesc())) {
            return TowardsType.NORTH.getValue();
        } else {
            return TowardsType.OTHER.getValue();
        }
    }

    /**
     * 获取租赁方式
     *
     * @param str
     * @return
     */
    private Integer getRentType(String str) {
        if (str.contains(RentType.ENTIRE_RENT.getDesc())) {
            return RentType.ENTIRE_RENT.getValue();
        } else {
            return RentType.SHARE_RENT.getValue();
        }
    }

    private String getHouseTypeByStr(String str) {
       return StringUtils.split(str, '：')[1];
    }

    private Integer getTimeByStr(String str) {
        if (str.contains(ViewingTimeType.MORNING.getDesc())) {
            return ViewingTimeType.MORNING.getValue();
        } else if (str.contains(ViewingTimeType.NOON.getDesc())) {
            return ViewingTimeType.NOON.getValue();
        } else if (str.contains(ViewingTimeType.AFTERNOON.getDesc())) {
            return ViewingTimeType.AFTERNOON.getValue();
        } else if (str.contains(ViewingTimeType.NIGHT.getDesc())) {
            return ViewingTimeType.NIGHT.getValue();
        } else if (str.contains(ViewingTimeType.ALL.getDesc())) {
            return ViewingTimeType.ALL.getValue();
        } else {
            return ViewingTimeType.OTHER.getValue();
        }
    }
}
